package com.longsong.mqtt_project;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;


import com.longsong.mqtt_project.databinding.ActivityMainBinding;
import com.xuexiang.xui.widget.popupwindow.status.Status;
import com.xuexiang.xui.widget.toast.XToast;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding mViewBinding;
    private static String TAG = MainActivity.class.getSimpleName();
    private static MqttAndroidClient mqttAndroidClient;
    private boolean isChecked ;
    private Handler mHandler;
    private Intent intent;
    private int count=0;
    private ArrayList<Entry> list_wd=new ArrayList<>();
    private ArrayList<Entry> list_sd=new ArrayList<>();

    //自动消失
    private Runnable mAutoDismiss = new Runnable() {
        @Override
        public void run() {
            if (mViewBinding.status.getStatus()==Status.CUSTOM) {
                mViewBinding.status.dismiss();
            }
            mHandler.removeCallbacks(mAutoDismiss);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mViewBinding.getRoot());
        mHandler = new Handler();

        mViewBinding.editMsg.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        //文本显示的位置在EditText的最上方
        mViewBinding.editMsg.setGravity(Gravity.TOP);
        //改变默认的单行模式
        mViewBinding.editMsg.setSingleLine(false);
        //水平滚动设置为False
        mViewBinding.editMsg.setHorizontallyScrolling(false);



        //  确认按钮状态
        isChecked = mViewBinding.sbIos.isChecked() ;
        mViewBinding.sbIos.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isChecked = b;
            }
        });


        mViewBinding.sbIos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isChecked){
                    mViewBinding.status.setStatus(Status.LOADING);
                    connect();
//                    }

                }else {
                    if (mqttAndroidClient != null) {
                        try {
                            IMqttToken mqttToken = mqttAndroidClient.disconnect();//断开连接
                            mqttToken.setActionCallback(new IMqttActionListener() {
                                @Override
                                public void onSuccess(IMqttToken iMqttToken) {
//                                    System.out.println("test if");
                                    mViewBinding.status.setStatus(Status.CUSTOM);
                                    mHandler.removeCallbacksAndMessages(null);
                                    mHandler.postDelayed(mAutoDismiss, 1500);
                                    mViewBinding.lineChart.setVisibility(View.INVISIBLE);
                                    mViewBinding.editMsg.setVisibility(View.INVISIBLE);
                                }

                                @Override
                                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
                                    Toast toast = Toast.makeText(MainActivity.this, "关闭失败", Toast.LENGTH_SHORT);
                                    toast.show();
                                    mViewBinding.sbIos.toggle();
                                }
                            });
                        } catch (MqttException e) {
                            e.printStackTrace();
                        }finally {
                            mqttAndroidClient = null;
                        }
                    }else {
//                        System.out.println("test else");
                        mViewBinding.status.setStatus(Status.CUSTOM);
                        mHandler.removeCallbacksAndMessages(null);
                        mHandler.postDelayed(mAutoDismiss, 1500);
                    }
                }
            }
        });


        mViewBinding.btSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isChecked&&mViewBinding.status.getStatus()!=Status.LOADING){
                    String topicStr = mViewBinding.etTopic.getEditValue();
                    if (!topicStr.isEmpty()){
                        subscribeTopic(topicStr);
                    }else {
                        Toast toast = Toast.makeText(MainActivity.this, "输入为空", Toast.LENGTH_SHORT);
                        toast.show();
                    }
                }else {
                    Toast toast = Toast.makeText(MainActivity.this, "请先连接", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
        });


        mViewBinding.lineChart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intent =new Intent(MainActivity.this,ChartActivity.class);//获得子界面的信息
                assert (intent!=null);
                intent.putExtra("list1",  list_wd);
                intent.putExtra("list2",  list_sd);
                startActivity(intent);
            }
        });

    }

    public void connect() {
        String host = mViewBinding.stvHost.getCenterEditValue();
        //使用uuid生成客户id
        String clientId = UUID.randomUUID().toString().replaceAll("-","");
        String userName = mViewBinding.stvUsername.getCenterEditValue();
        String passWord = mViewBinding.stvPassword.getCenterEditValue();

        if (host.isEmpty()) {
            Toast toast = Toast.makeText(MainActivity.this, "地址为空", Toast.LENGTH_SHORT);
            toast.show();
            mViewBinding.sbIos.toggle();
            mViewBinding.status.dismiss();
            return;
        }

        /* 创建MqttConnectOptions对象，并配置username和password。 */
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setConnectionTimeout(5);//5秒连不上断线

        if (!userName.isEmpty()) {
            mqttConnectOptions.setUserName(userName);
        }
        if (!passWord.isEmpty()) {
            mqttConnectOptions.setPassword(passWord.toCharArray());
        }


        /* 创建MqttAndroidClient对象，并设置回调接口。 */
        mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), host, clientId);


        /* 建立MQTT连接。 */
        try {
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    mViewBinding.status.setStatus(Status.COMPLETE);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    mViewBinding.status.setStatus(Status.ERROR);
                    mViewBinding.sbIos.toggle();
                    exception.printStackTrace();
                }
            });

        } catch (MqttException e) {
            e.printStackTrace();
        }

        mqttAndroidClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {

                if (isChecked==true){
                    mViewBinding.sbIos.toggle();
                    Toast toast = Toast.makeText(MainActivity.this, "连接掉线", Toast.LENGTH_SHORT);
                    toast.show();
                    mViewBinding.status.setStatus(Status.CUSTOM);
                    mHandler.removeCallbacksAndMessages(null);
                    mHandler.postDelayed(mAutoDismiss, 1500);
                }


            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                String msg = new String(message.getPayload());
                mViewBinding.editMsg.append("topic："+topic+"\nmsg："+msg+"\n");
                //做数据获取
                Map<String, Object> map = JSONObject.parseObject(msg, new TypeReference<Map<String, Object>>() {});//json字符串转Map
                String analysis = map.get("rs485").toString();
                String temperature; //温度
                String humidity;    //湿度

                if (!analysis.isEmpty()){//分析温湿度
//                    Log.i(TAG,"rs485:"+analysis);
                        temperature = String.valueOf((Integer.valueOf(analysis.substring(10,14), 16).shortValue())/10.0);
                        humidity = String.valueOf((Integer.valueOf(analysis.substring(6,10), 16).shortValue())/10.0);
                        mViewBinding.editMsg.append("温度:"+temperature+"℃\n湿度"+humidity+"%RH\n");
//                        System.out.println("温度"+temperature+"℃");
//                        System.out.println("湿度"+humidity+"%RH");
                        list_wd.add(new Entry(count, (float) Double.parseDouble(temperature)));
                        list_sd.add(new Entry(count, (float) Double.parseDouble(humidity)));
                        count++;
                }

            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                Toast toast = Toast.makeText(MainActivity.this, "已发送", Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }

    public void subscribeTopic(String topic) {
        try {
            mqttAndroidClient.subscribe(topic, 0, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Toast toast = Toast.makeText(MainActivity.this, "订阅成功>topic:" + topic, Toast.LENGTH_SHORT);
                    toast.show();
                    mViewBinding.editMsg.setVisibility(View.VISIBLE);
                    mViewBinding.lineChart.setVisibility(View.VISIBLE);
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Toast toast = Toast.makeText(MainActivity.this, "订阅失败>topic:" + topic, Toast.LENGTH_SHORT);
                    toast.show();
                    String msg = "";
                    if (exception != null) {
                        msg = "," + exception.getMessage();
                        exception.printStackTrace();
                    } else {
                        msg = "未知错误！";
                    }
                    toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT);
                    toast.show();
                }
            });

        } catch (MqttException e) {
            Log.i(TAG, "订阅失败>topic:" + topic);
            String msg = "";
            if (e != null) {
                msg = "," + e.getMessage();
                e.printStackTrace();
            } else {
                msg = "未知错误！";
            }
            Toast toast = Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT);
            toast.show();
        }
    }
}